package com.zzt.questionbankusermanager.bean.dto.query;

import com.zzt.questionbankusermanager.bean.MenuItem;
import lombok.Data;
import org.springframework.data.jpa.domain.Specification;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Data
public class MenuItemQueryDTO {
    private String alias;
    private String parent_menu_id;
    private Integer page;
    private Integer size;

    public Specification< MenuItem > getWhereClause(){
        String alias=this.alias;
        String parent_menu_id=this.parent_menu_id;
        return new Specification< MenuItem >() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root< MenuItem > root, CriteriaQuery< ? > criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(alias)){
                    predicates.add(criteriaBuilder.like(root.get("alias").as(String.class), "%"+alias+"%"));
                }
                if (StringUtils.isNotBlank(parent_menu_id)){
                    predicates.add(criteriaBuilder.like(root.get("parent_menu_id").as(String.class), "%"+parent_menu_id+"%"));
                }
                Predicate[] pre = new Predicate[predicates.size()];
                return criteriaQuery.where(predicates.toArray(pre)).getRestriction();
            }
        };
    }
}
